package com.zsk.shop.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.api.bankcard.AliYunBankCardCheck;
import com.zsk.shop.api.bankcard.AliYunBankCardResult;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.utils.BankUtils;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.BankCardUser;
import com.zsk.shop.entity.ShopUser;
import com.zsk.shop.mapper.BankCardUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ys
 * @date 2021年12月13日 10:09
 */
@Service
public class BankCardService extends ServiceImpl<BankCardUserMapper, BankCardUser> {

    private static final Logger logger = LoggerFactory.getLogger(BankCardService.class);

    @Resource
    private ShopUserService userService;

    @Resource
    private BankUtils bankUtils;
    @Resource
    private AliPayAccountUserService aliPayAccountUserService;

    @Autowired
    private AliYunBankCardCheck aliYunBankCardCheck;

    public List<BankCardUser> getBankCardInfo(String userNo) {
        LambdaQueryWrapper<BankCardUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BankCardUser::getUserNo, userNo);
        queryWrapper.eq(BankCardUser::getIsDeleted, false);
        queryWrapper.orderByDesc(BankCardUser::getCreateTime);
        return list(queryWrapper);
    }

    public BankCardUser getDefaultBankCardInfo(String userNo) {
        LambdaQueryWrapper<BankCardUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BankCardUser::getUserNo, userNo);
        queryWrapper.eq(BankCardUser::getIsDeleted, false);
        queryWrapper.orderByDesc(BankCardUser::getIsDefault);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

    public synchronized BaseResponse addBankCardUser(String bankCardId, String bankNo, String bankName, String phone, String subName) {
        //获取用户实名名称
        String userNo = HttpContext.getUserNo();
        ShopUser userInfo = userService.queryByUserNo(userNo);
        if (ToolUtil.isNotEmpty(userInfo)) {
            if (ToolUtil.isEmpty(userInfo.getTrueName()) || ToolUtil.isEmpty(userInfo.getIdentityCard())) {
                return BaseResponse.error("当前账号未实名，请完成实名操作");
            }
        }
//        //检查是否为支付宝，如果是则添加至支付宝账户
//        if (bankNo.equals("ALIPAY")) {
//            aliPayAccountUserService.add(phone);
//            return BaseResponse.success("添加支付宝账户成功。");
//        }
        //检查卡号是否已被账号绑定
//        if (!getListByCardId(bankCardId).isEmpty()) {
//            return BaseResponse.error("当前账号已被绑定");
//        }
        String bizNo = userNo;
        String userName = userInfo.getTrueName();
        //获取银行数据 bankNo 通过列表获取
        String bankNoGet = bankUtils.getBankNo(bankCardId);
        if (ToolUtil.isEmpty(bankNoGet)) {
            return BaseResponse.error("当前所属银行信息获取失败");
        } else {
            if (!bankNoGet.equals(bankNo)) {
                return BaseResponse.error("当前所属银行信息不一致");
            }
        }
        //检验所属银行
        String bankNameGet = bankUtils.getBankNameByBankNo(bankNo);
        if (!bankNameGet.equals(bankName)) {
            return BaseResponse.error("当前银行不一致，操作失败");
        }
        String bankIcon = bankUtils.getBankIcon(bankNo);
        String msg = checkBankCardInfoSuccess(userName, bankCardId, phone);
        if (ToolUtil.isNotEmpty(msg)) {
            return BaseResponse.error(msg);
        }
        //添加银行卡数据
        BankCardUser user = BankCardUser.builder()
                .userNo(bizNo).userName(userName).bankCardId(bankCardId).bankNo(bankNo).bankName(bankName).subName(subName).bankIcon(bankIcon).phone(phone).isDeleted(false).createTime(new Date()).build();
        //如果是单卡则设置为默认卡
        if (ToolUtil.isEmpty(getBankCardInfo(bizNo))) {
            user.setIsDefault(true);
        }
        this.save(user);
        return BaseResponse.success();
    }

    private List<BankCardUser> getListByCardId(String bankCardId) {
        LambdaQueryWrapper<BankCardUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BankCardUser::getBankCardId, bankCardId);
        queryWrapper.eq(BankCardUser::getIsDeleted, false);
        List<BankCardUser> list = this.list(queryWrapper);
        return list;
    }

    /**
     * 银行号二要素 名称+卡号
     *
     * @param trueName
     * @param bankCardId
     * @return
     */
    public String checkBankCardInfoSuccess(String trueName, String bankCardId, String phone) {
        AliYunBankCardResult result = aliYunBankCardCheck.check(trueName, bankCardId, null, null);
        logger.info(trueName + "|" + bankCardId + "|" + phone + "|"
                + JSON.toJSONString(result));
        if (!result.getResult().equals("T")) {
            return result.getMessage();
        }
        return "";
    }

//    /**
//     * 银行号二要素 名称+卡号
//     *
//     * @param trueName
//     * @param bankCardId
//     * @return
//     */
//    public String checkBankCardInfoSuccess(String trueName, String bankCardId) {
//        String result = TencentBankCard2EVerification.bankCard2EVerification(trueName, bankCardId);
//        String str = "";
//        if (ToolUtil.isNotEmpty(result) && result.equals("0")) {
//            return str;
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-4")) {
//            str = "持卡人信息有误";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-5")) {
//            str = "未开通无卡支付";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-6")) {
//            str = "此卡被没收";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-7")) {
//            str = "无效卡号";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-11")) {
//            str = "此卡已挂失";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-14")) {
//            str = "密码错误次数超限";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-15")) {
//            str = "发卡行不支持此交易";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-2")) {
//            str = "姓名校验不通过";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-3")) {
//            str = "银行卡号码有误";
//        } else if (ToolUtil.isNotEmpty(result) && result.equals("-16")) {
//            str = "验证中心服务繁忙";
//        } else {
//            str = "认证未通过";
//        }
//        str += ",姓名:" + trueName + ",卡号：" + bankCardId;
//        return str;
//    }

    public String getBankNo(String bankCardId) {
        return bankUtils.getBankNo(bankCardId);
    }

    public BaseResponse getBankNameByCardId(String bankCardId) {
        String bankNo = this.getBankNo(bankCardId);
        String bankName = bankUtils.getBankNameByBankNo(bankNo);
        return BaseResponse.success(bankName);
    }

    public BaseResponse getBankInfoList() {
        List<BankUtils.Bank> bankList = bankUtils.getAllBank();
        bankList = bankList.stream().sorted(Comparator.comparing(BankUtils.Bank::getSort)).collect(Collectors.toList());
        return BaseResponse.success(bankList);
    }

    public BaseResponse deletedBankCard(Long id) {
        BankCardUser bankCard = this.getById(id);
        if (ToolUtil.isEmpty(id)) {
            return BaseResponse.error("当前数据不存在");
        }
        bankCard.setIsDeleted(true);
        this.updateById(bankCard);
        return BaseResponse.success("删除银行卡成功");
    }

    public BankCardUser getByBankCardNumber(String bankCardNumber) {
        LambdaQueryWrapper<BankCardUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BankCardUser::getBankCardId, bankCardNumber);
        queryWrapper.eq(BankCardUser::getIsDeleted, false);
        queryWrapper.orderByDesc(BankCardUser::getIsDefault);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }
}
